package org.kev.transit.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.commons.httpclient.HttpException;
import org.json.JSONException;
import org.kev.transit.TransitProvider;
import org.kev.transit.util.JsonHelper;
import org.kev.transit.util.WebHelper;
import org.kev.transit.worker.StopUpdateWorker;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

/**
 * Stop table
 */
public final class Stop implements BaseColumns {


	/**
	 * The default sort order for this table
	 */
	public static final String DEFAULT_SORT_ORDER = "stop._id DESC";
	/**
	 * route_type
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String ROUTE_TYPE = "route_type";
	/**
	 * sopt_id
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String STOP_ID = "stop_id";

	/**
	 * direction of route
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String DIRECTION = "direction";

	/**
	 * direction of route
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String ROUTE = "route";  
	/**
	 * The title of station
	 * <P>Type: TEXT</P>
	 */
	public static final String TITLE = "title";

	/** Latitude */
	public static final String LAT = "lat";
	/** longitude */
	public static final String LON = "lon";
	public static final String CREATE_DATE = "create_date";
	public static final String TABLE_NAME = "stop";
	public static final Uri CONTENT_URI = Uri.parse("content://"+TransitProvider.AUTH+"/"+TABLE_NAME);

	private static final String TAG = "Stop";
	public String id = null;
	public String routeTypeId = null;
	public String routeId = null;
	public String directionId = null;
	public String title = null;
	public String lat = null;
	public String lon = null;
	public long createDate = 0;

	public  Stop(String id, String name, String lat, String lon) {
		this.id = id;
		this.title = name;
		this.lat = lat;
		this.lon = lon;
	} 
	public  Stop() {
	} 	

	public static ArrayList <Stop> getData(Activity parent,String rType, String route,String dir){
		Log.d(TAG,">>> getData");

		ArrayList <Stop> list = new ArrayList <Stop>();
		if(parent==null | rType==null|| route==null|| dir==null){
			Log.e(TAG," getData has null parms"+parent+rType+route+dir);
			return list;
		}
		Cursor cursor = null;
		String where = 
			Stop.ROUTE_TYPE + "=? AND "+  
			Stop.ROUTE + "=? AND " +
			Stop.DIRECTION + "=? ";
		String args[]={rType,route,dir};
		boolean foundData =false;
		try {
			cursor = parent.managedQuery(Stop.CONTENT_URI, new String[] {
					Stop.STOP_ID, 
					Stop.TITLE,
					Stop.LAT,
					Stop.LON,
					Stop.ROUTE_TYPE,
					Stop.ROUTE,
					Stop.DIRECTION,
					Stop.CREATE_DATE }, where, args,null);

			while (cursor.next()) {
				foundData=true;
				Stop stop = new Stop();
				stop.id = cursor.getString(0);
				stop. title = cursor.getString(1);
				stop.lat= cursor.getString(2);
				stop.lon = cursor.getString(3);
				stop.routeTypeId = cursor.getString(4);
				stop.routeId = cursor.getString(5);
				stop.directionId = cursor.getString(6);
				stop.createDate=cursor.getLong(7);
				//Log.d(TAG,"db obj="+stop.toXml());
				list.add(stop);
			}
		}finally {
			if (cursor != null)
				cursor.close();
		}

		//long time=System.currentTimeMillis();
		//Date date = new Date(time);
		//date.
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.YEAR, -1);
		long lastYear = cal.getTimeInMillis();
		Log.d(TAG,"lastYear="+lastYear);
		//Stop s = list.get(1);
		if(!foundData ){
			try {
				list=retrieveDataFromWeb(parent,rType,route,dir);
			} catch (Exception e) {
				Log.e(TAG,"Unable to retrieve data from web!",e);
			} 					
		}

		Log.d(TAG,"<<< getData"+list);
		return list;
	}
	/**
	 * 
	 * @param parent
	 * @param rType
	 * @param route
	 * @param dir
	 * @return list of data objects
	 * @throws HttpException
	 * @throws IOException
	 * @throws JSONException
	 */
	private static ArrayList <Stop> retrieveDataFromWeb(Activity parent,String rType, String route,String dir) throws HttpException, IOException, JSONException{
		Log.d(TAG,"did not find any data in tables get it from the web");
		String jsonText=null;
		jsonText=WebHelper.getStop(rType, route, dir);
		ArrayList <Stop> list= new ArrayList <Stop>();
		list= JsonHelper.getStops(jsonText);
		Log.d(TAG,"Retrieved data from web="+list.size());
		/*for(int i=0;i<list.size();i++){
			Stop stop = list.get(i);
			Log.d(TAG,"stop="+stop.toXml());
		}*/
		StopUpdateWorker worker=null;
		//update db in background
		worker = new StopUpdateWorker(parent, list);
		Thread t = new Thread(worker);
		t.start();
		//worker.run();
		return list;
	}
	/**
	 * dumps current instance values to a string 
	 * in a XML format
	 * @return XML
	 */
	public String toXml(){
		return
		"<"+TABLE_NAME+">\n"+
		"\t<"+Stop.STOP_ID+">"+id+"</"+Stop.STOP_ID+">\n"+
		"\t<"+Stop.TITLE+">"+title+"<"+Stop.TITLE+">\n"+
		"\t<"+Stop.ROUTE_TYPE+">"+routeTypeId+"</"+Stop.ROUTE_TYPE+">\n"+
		"\t<"+Stop.ROUTE+">"+routeId+"</"+Stop.ROUTE+">\n"+
		"\t<"+Stop.DIRECTION+">"+directionId+"</"+Stop.DIRECTION+">\n"+
		"\t<"+Stop.LAT+">"+lat+"</"+Stop.LAT+">\n"+
		"\t<"+Stop.LON+">"+lon+"</"+Stop.LON+">\n"+
		"\t<"+Stop.CREATE_DATE+">"+createDate+"</"+Stop.CREATE_DATE+">\n"+
		"</"+TABLE_NAME+">\n" ;
	}
	@Override
	/**
	 * 
	 */
	public String toString(){
		return title;
	}

} //End Base Columns
